package com.xiaoshu.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 功能说明：
 * com.ubtechinc.config
 *
 * <p>
 * Original @Author: deane.jia-贾亮亮,2021/3/19 15:31
 * <p>
 * Copyright (C)2012-2021 深圳优必选科技 All rights reserved.
 */
@Configuration
@Slf4j
public class DoubleRedisConfiguration {

    @Value("${spring.redis.master.host}")
    private String masterHost;

    @Value("${spring.redis.master.port}")
    private int masterPort;

    @Value("${spring.redis.master.password}")
    private String masterPassword;

    @Value("${spring.redis.master.database}")
    private int masterDataBase;

    @Value("${spring.redis.slave.host}")
    private String slaveHost;

    @Value("${spring.redis.slave.port}")
    private int slavePort;

    @Value("${spring.redis.slave.password}")
    private String slavePassword;

    @Value("${spring.redis.slave.database}")
    private int slaveDataBase;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.jedis.pool.max-total}")
    private int maxTotal;

    @Value("${spring.redis.jedis.pool.max-wait}")
    private int maxWait;

    @Bean(name = "masterRedisTemplate")
    public RedisTemplate<String, Object> masterRedisTemplate(){
        log.info("[Master redis template] start up the redis template host:{}", masterHost);
        RedisConnectionFactory factory =
                this.connectionFactory(masterHost, masterPort, masterPassword, maxIdle, maxTotal, maxWait, masterDataBase);
        return this.redisTemplate(factory);
    }

    @Bean(name = "slaveRedisTemplate")
    public RedisTemplate<String, Object> slaveRedisTemplate(){
        log.info("[slave redis template] start up the redis template host:{}", slaveHost);
        RedisConnectionFactory factory =
                this.connectionFactory(slaveHost, slavePort,slavePassword, maxIdle, maxTotal, maxWait, slaveDataBase);
        return this.redisTemplate(factory);
    }

    /**
     *
     * @param host
     * @param port
     * @param password
     * @param maxIdle
     * @param maxTotal
     * @param maxWaitMillis
     * @param index
     * @return
     */
    public RedisConnectionFactory connectionFactory(String host, int port, String password, int maxIdle,
                                                    int maxTotal, long maxWaitMillis, int index) {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName(host);
        jedisConnectionFactory.setPort(port);
        if (!StringUtils.isEmpty(password)) {
            jedisConnectionFactory.setPassword(password);
        }

        if (index != 0) {
            jedisConnectionFactory.setDatabase(index);
        }

        jedisConnectionFactory.setPoolConfig(poolConfig(maxIdle, maxTotal, maxWaitMillis, false));
        jedisConnectionFactory.afterPropertiesSet();
        return jedisConnectionFactory;
    }


    /**
     * 连接池配置
     * @param maxIdle
     * @param maxTotal
     * @param maxWaitMillis
     * @param testOnBorrow
     * @return
     */
    public JedisPoolConfig poolConfig(int maxIdle, int maxTotal, long maxWaitMillis, boolean testOnBorrow) {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMaxTotal(maxTotal);
        poolConfig.setMaxWaitMillis(maxWaitMillis);
        poolConfig.setTestOnBorrow(testOnBorrow);
        return poolConfig;
    }

    /**
     *
     * @param factory
     * @return
     */
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setValueSerializer(stringRedisSerializer);
        template.setHashValueSerializer(stringRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}
